'use strict';
const { $, getDataByText, unitTime } = require('../utils/utils');

class Fund {
  constructor(requestReptile) {
    this.requestReptile = requestReptile;
  }

  async getETFInfo(code) {
    try {
      const url = `http://fund.eastmoney.com/f10/jbgk_${code}.html`;
      const html = await this.requestReptile(url, 'text');
      const obj = {};

      const target = $(html)('.box tr').eq(9).find('td').eq(1).text();
      if (target !== '该基金无跟踪标的') {
        obj.target = target;
      }

      const gm = parseFloat($(html)('.box tr').eq(3).find('td').eq(0).text());
      if (!isNaN(gm)) {
        obj.gm = gm;
      }

      return obj;
    } catch (e) {
      return null;
    }
  }

  async getETFBaseInfo() {
    try {
      const funds = await this.getETFList();
      const data = [];
      for await (const fund of funds) {
        const info = await this.getETFInfo(fund.code);
        if (info) {
          data.push({
            ...fund,
            ...info
          });
        }
      }
      return data;
    } catch (e) {
      return null;
    }
  }

  async getETFList() {
    const url = `http://38.push2.eastmoney.com/api/qt/clist/get?cb=callback&pn=1&pz=500&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid=f3&fs=b:MK0021,b:MK0022,b:MK0023,b:MK0024&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152&_=${unitTime()}`;
    const res = await this.requestReptile(url, 'text', 'callback');
    const data = getDataByText(res,
      { data: 'data', },
      'data.data.diff',
      'callback'
    );
    return data.map((
      { f2: current, f3: zdf, f4: change, f5: cjl, f6: cje, f7: zf, f8: hsl, f10: lb, f12: code, f14: name, f15: zg, f16: zd, f17: zs }
    ) => ({
      code,
      name,
      // 最高
      zg,
      // 最低
      zd,
      // 昨收
      zs,
      current,
      zdf,
      change,
      // 成交量
      cjl,
      // 成交额
      cje,
      // 振幅
      zf,
      // 换手率
      hsl,
      // 量比
      lb,
    }));
  }
}

module.exports = Fund;
